﻿#include "stacksetting.h"
#include <QCoreApplication>
#include <QFile>
#include "algorithm_log.h"

#define CONFIG_PATH "/config/stackCfg.json"

StackSetting::StackSetting()
{
}

StackSetting::~StackSetting()
{
}

static StackSetting* instance = nullptr;
StackSetting* StackSetting::GetInstance()
{
	if (instance == nullptr) {
		instance = new StackSetting();
	}
	return instance;
}

bool StackSetting::Init(bool reInit)
{
	m_shaps.clear();
	QString filename = QCoreApplication::applicationDirPath() + QString(CONFIG_PATH);
	QFile file(filename);
	if (!file.exists()) {
		log_error("Config file [{}] not find");
		return false;
	}
	if (!file.open(QIODevice::ReadOnly)) {
		log_error("file[{}] open failed", filename);
		return false;
	}

	QByteArray data = file.readAll();
	StackConfiguration allcfg = {};
	allcfg.fromJson(data);
	// 解析垛形形状信息
	for (auto iter : allcfg.shapList()) {
		if (m_shaps.find(iter.id()) == m_shaps.end()) {
			m_shaps.emplace(iter.id(), iter);
		} else {
			m_shaps[iter.id()] = iter;
		}
	}
	// 解析垛形信息
	for (auto iter : allcfg.stackList()) {
		if (m_stacks.find(iter.id()) == m_stacks.end()) {
			m_stacks.emplace(iter.id(), iter);
		} else {
			m_stacks[iter.id()] = iter;
		}
	}

	file.close();
	return true;
}

// 垛形形状配置接口
std::vector<int> StackSetting::GetShapList()
{
	std::vector<int> list;
	for (auto& iter : m_shaps) {
		list.push_back(iter.first);
	}
	return list;
}

ShapCfg StackSetting::GetShapCfgById(int id)
{
	if (m_shaps.find(id) != m_shaps.end()) {
		return m_shaps[id];
	}
	log_error("Not find shap id = {}", id);
	return {};
}

// 垛形信息接口
std::vector<int> StackSetting::GetStackIdList()
{
	std::vector<int> list;
	for (auto& iter : m_stacks) {
		list.push_back(iter.first);
	}
	return list;
}

StackCfg StackSetting::GetStackCfgById(int id)
{
	if (m_stacks.find(id) != m_stacks.end()) {
		return m_stacks[id];
	}
	log_error("Not find stack id = {}", id);
	return {};
}
